#!/bin/bash -e

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
    echo "Illegal number of parameters"
    exit 1
fi

TAG=$1
DRY_RUN=""
[ "$#" -eq 2 ] && DRY_RUN=$2

BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd $BASE

echo "---- Build Discuz Q Framework and Commit to Git Repo -----------------------------"

[ "$DRY_RUN" = "-n" ] && echo "Dry run, no changes will be pushed to remote"

# framework git仓库
FRAMEWORK_REPO="git@gitee.com:kotlindev/Discuz-Q-Framework.git"

function checkout_framework {
    cd $BASE
    echo "---- removing framework_temp"
    rm -rf $BASE/framework_temp
    echo "---- clone new copy of Discuz to framework_temp"
    git clone $FRAMEWORK_REPO framework_temp

}

function checkout_tag_as_branch {
    cd $1
    echo "---- checking out tag $TAG as branch br_$TAG under $1"
    git checkout -b br_$TAG $TAG
}

function patch_version_in_source {
    cd $BASE/framework_temp
    echo "---- replacing version tag"
    tag_value="${TAG:1}"
    sed  -i "s/\(.*\)\(const VERSION = '\)\(.*\)\(';\)/\1\2$tag_value\4/g" src/Foundation/Application.php
}

function commit_all {
    cd $BASE/framework_temp
    git add .
    git diff-index --quiet HEAD || git commit -m "auto versioning by bot"
}

function retag_repo {
    cd $BASE/framework_temp
    echo "---- delete old tag"
    git tag -d $TAG
    echo "---- make new tag"
    git tag $TAG
}

function push_to_remote {
    if [ ! "$DRY_RUN" = "-n" ]; then
        echo "---- push to build repo"
        git remote add build $FRAMEWORK_REPO
        git push build $TAG -f
    else
        echo "---- Dry run mode, do not actually push"
    fi
}

checkout_framework
checkout_tag_as_branch $BASE/framework_temp
patch_version_in_source
commit_all
retag_repo
push_to_remote
